'use strict';
const fs = require('fs');
const path = require('path');

//故名思意 异步二进制 写入流
const awaitWriteStream = require('await-stream-ready').write;
//管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole');

const Service = require('egg').Service;

class CommonService extends Service {
    async upload(stream) {
        let { ctx } = this;
        let filename = stream.filename;
        let day = Math.random().toString(36).substr(2) + (new Date().getTime()) + Math.floor(Math.random()*10) + Math.floor(Math.random()*10);
        let target = path.join(this.config.pathConfig.uploadPath, day+escape(filename));

        if (!fs.existsSync(this.config.pathConfig.uploadPath)) {
            fs.mkdir(this.config.pathConfig.uploadPath, () => {});
        }
        let writeStream = fs.createWriteStream(target); //创建文件流
        try {
            await awaitWriteStream(stream.pipe(writeStream));
            //console.log("成功")
            let url = this.config.pathConfig.domainName + '/public/upload/' + day+escape(filename);
            return {
                code: 1,
                url: url
            }
        } catch (err) {
            await sendToWormhole(stream); // 失败，关闭文件流
            //console.log("失败")
            return {
                code: 0
            }
        }

    }
}

module.exports = CommonService;
